angular.module('Caltech').controller('equipmentController', function ($scope, Restangular, ngTableParams, $stateParams, $location) {
    'use strict';

    $scope.filters = {};

    $scope.search = function (index) {
        if ($scope.tableParams) {
            $scope.tableParams.reload();
        } else {
            $scope.tableParams = new ngTableParams({
                page: index || 1,
                count: 10
            }, {
                counts: [],
                getData: function ($defer, params) {
                    var model = $scope.filters.model;
                    Restangular.all('equipment')
                        .getList({
                            page: params.page(),
                            count: params.count(),
                            model: model || undefined
                        }).then(function (equipment) {
                            params.total(equipment.total);
                            $defer.resolve(equipment);

                            if (params.page() > 1) {
                                $location.search('pageIndex', params.page());
                            }
                            $location.search('model', model || undefined);
                        });
                }
            });
        }

    };

    $scope.getCustomerList = function (nameFitler) {
        return Restangular.all('customer/list').getList({
            name: nameFitler
        });
    };

    $scope.updateState = function (item) {
        if (!item) {
            $scope.customer = {};
        } else if (typeof (item) === 'object') {
            $scope.customer = item;

            $location.search('customerId', item.id);
            $location.search('customerName', item.name);

            if ($scope.tableParams) {
                $scope.tableParams.reload();
            } else {
                $scope.search();
            }
        }
    };

    $scope.import = function (file) {
        alert('Being developed');
    };

    if ($stateParams.model || $stateParams.pageIndex) {
        $scope.filters.model = $stateParams.model;
        $scope.search($stateParams.pageIndex);
    } else {
        $scope.search();
    }
});